import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User } from '@/types'
import { authAPI } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref<User | null>(null)
  const isAuthenticated = ref(!!token.value)

  const login = async (username: string, password: string) => {
    try {
      const response = await authAPI.login(username, password)
      token.value = response.token
      user.value = response.user
      isAuthenticated.value = true
      
      localStorage.setItem('token', token.value)
      return response
    } catch (error) {
      throw error
    }
  }

  const logout = () => {
    token.value = ''
    user.value = null
    isAuthenticated.value = false
    localStorage.removeItem('token')
  }

  const checkAuth = async () => {
    if (!token.value) {
      logout()
      return false
    }

    try {
      // 这里可以添加验证token有效性的API调用
      return true
    } catch (error) {
      logout()
      return false
    }
  }

  return {
    token,
    user,
    isAuthenticated,
    login,
    logout,
    checkAuth
  }
})